package com.common.util.repay_plan;

import com.common.util.date.DateUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

/**
 * @describe: 等本等息
 */
class EqualPrincipalAndInterest {

    /**
     * 等本等息
     *    每月本金 = 本金/期数
     *    每月利息 = 本金 * 转换后的对应期数利率
     *    还款总额 = （每月本金+每月利息）*期数
     * @return
     */
    protected static ArrayList<RepayPlan> getPlan(RepayPlanCondition repayPlanCondition) {
        Date startTime = repayPlanCondition.getStartTime();  //计息开始时间
        int loanDays = repayPlanCondition.getLoanDays();     //借款天数
        int fixedRepayDay = repayPlanCondition.getFixedRepayDay();   //固定还款日
        BigDecimal amt = repayPlanCondition.getAmt();      //借款总金额
        BigDecimal rate = repayPlanCondition.getRate();      //年化利率
        int annualNumberOfDays = repayPlanCondition.getAnnualNumberOfDays();  //年化天数

        // 获取每一期对应的时间
        ArrayList<Date> repayDate = RepayDateUtil.getRepayDate(startTime, loanDays, fixedRepayDay, RepayDateUtil.PeriodsUnit.MONTH);
        int period = repayDate.size();

        BigDecimal results = amt.divide(BigDecimal.valueOf(period), 2, BigDecimal.ROUND_HALF_UP);
        ArrayList<BigDecimal> periodCapital = new ArrayList<>(period);
        for (int i = 0; i < period; i++) {
            periodCapital.add(results);
        }

        BigDecimal lastPeriodCapital = amt.subtract(results.multiply(new BigDecimal(period - 1)));
        periodCapital.set(period - 1, lastPeriodCapital);
        
        //利率转化，目前只支持月利率，暂不转换
        BigDecimal interest = amt.multiply(new BigDecimal(30)).multiply(rate)
                                 .divide(new BigDecimal(annualNumberOfDays), 2, BigDecimal.ROUND_HALF_UP);

        ArrayList<RepayPlan> repayPlans = new ArrayList<>(period);
        for (int i = 0; i < period; i++) {
            RepayPlan repayPlan = new RepayPlan();
            if (i == 0) {
                repayPlan.setStartDate(startTime);
            } else {
                Date startDate = DateUtil.getBeginTime(DateUtil.addMillSecond(repayDate.get(i - 1), 1));
                repayPlan.setStartDate(startDate);
            }
            repayPlan.setEndDate(repayDate.get(i));   //应还款日期
            repayPlan.setPrincipal(periodCapital.get(i));  //应还本金
            repayPlan.setInterest(interest);      //应还利息
            repayPlan.setLastPrincipal(i== 0 ? amt : repayPlans.get(i - 1).getLastPrincipal()
                                                    .subtract(repayPlans.get(i - 1).getPrincipal()));  //剩余应还本金
            repayPlan.setInterestDays(DateUtil.getIntervalDays_1(repayPlan.getEndDate(), repayPlan.getStartDate()));
            repayPlans.add(repayPlan);
        }
        return repayPlans;
    }
}
